package com.jingdianjichi.subject.domain.handler.subject;

import com.google.common.base.Preconditions;
import com.jingdianjichi.subject.common.enums.ISDeletedFlagEnum;
import com.jingdianjichi.subject.common.enums.SubjectInfoTyperEnum;
import com.jingdianjichi.subject.domain.convert.JudgeSubjectBoConverter;
import com.jingdianjichi.subject.domain.entity.SubjectAnswerBo;
import com.jingdianjichi.subject.domain.entity.SubjectInfoBo;
import com.jingdianjichi.subject.domain.entity.SubjectOptionBo;
import com.jingdianjichi.subject.infra.basic.entity.SubjectJudge;
import com.jingdianjichi.subject.infra.basic.service.SubjectJudgeService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;

/**
 * 单选题目的策略类
 */
@Component
public class JudgeTypeHandler implements SubjectTypeHandler{
    @Override
    public SubjectInfoTyperEnum getHandlerType() {
        return SubjectInfoTyperEnum.JUDGE;
    }

    @Resource
    private SubjectJudgeService subjectJudgeService;
    @Override
    public void add(SubjectInfoBo subjectInfoBo) {
        List<SubjectJudge> subjectJudgeList=new LinkedList<>();
        //判断题目插入
        Preconditions.checkNotNull(subjectInfoBo.getOptionList(),"选项不能为空");

        try {
            subjectInfoBo.getOptionList().forEach(judge->{
                SubjectJudge subjectJudge = JudgeSubjectBoConverter.INSTANCE.convertAnswerBoToJudgeEntity(judge);
                subjectJudge.setSubjectId(subjectInfoBo.getId());
                subjectJudge.setIsDeleted(ISDeletedFlagEnum.UN_DELETE.getCode());
                subjectJudgeList.add(subjectJudge);
            });
        } catch (Exception e) {
            throw new RuntimeException("判断题集合为空");
        }
        subjectJudgeService.insertBatch(subjectJudgeList);
    }

    @Override
    public SubjectOptionBo query(Integer subjectId) {
        SubjectJudge subjectJudge = new SubjectJudge();
        subjectJudge.setSubjectId(Long.valueOf(subjectId));
        List<SubjectJudge> result = subjectJudgeService.queryByCondition(subjectJudge);
        List<SubjectAnswerBo> subjectAnswerBOList = JudgeSubjectBoConverter.INSTANCE.convertEntityToBoList(result);
        SubjectOptionBo subjectOptionBO = new SubjectOptionBo();
        subjectOptionBO.setOptionList(subjectAnswerBOList);
        return subjectOptionBO;

    }
}
